<template>
  <div class="approval-form" v-loading="loading">
    <el-button type="text" icon="el-icon-arrow-left" v-if="!instanceId" @click="handleBack">返回</el-button>
    <div class="apply-upload" v-if="!instanceId">
      <div class="apply-upload-title">申请材料</div>
      <div v-for="item in fileList" :key="item.uid" class="apply-upload-name" @click="lookFile(item)">
        {{ item.name }}
      </div>
      <el-upload class="upload-demo" :headers="upload.headers" :action="upload.url" accept=".pdf, .jpg, .png,.PNG,.PDF"
        multiple :show-file-list="false" :on-success="handleChange" :file-list="fileList" :before-upload="beforeUpload">
        <el-button size="small" type="primary">上传文件</el-button>
        <div slot="tip" class="el-upload__tip">支持扩展名:.pdf .jpg</div>
      </el-upload>
    </div>
    <f-render v-if="flag" :loading="loading" :isShowSubmitBtn="isShowSubmitBtn" v-model="formData"
      :request-fn="handleSubmit" :config="formConfig" :pure="pure" />
  </div>
</template>

<script>
import {
  getFormById,
  getFormKeyByDefId,
  getFromAndData,
} from "@/api/internalApproval/myApplication.js";
import { getToken } from "@/utils/auth";
export default {
  name: "Form",
  componentName: "Form",
  data() {
    return {
      loading: false,
      pure: false,
      formData: {},
      formConfig: "",
      operateType: "add", // 操作类型
      showTip: false,
      detail: {},
      flag: false,
      formItemDoList: [],
      formDetail: {},
      fileList: [],
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/auditFeign/common/upload",
      },
    };
  },
  props: {
    processDefinitionId: {
      type: String,
      required: false,
    },
    instanceId: {
      type: String,
      required: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    isShowSubmitBtn: {
      type: Boolean,
      default: false,
    },
  },
  methods: {
    // 上传前判断文件类型
    beforeUpload(file) {
      // 截取上传文件的后缀名
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      //判断多个
      if (!["pdf", "png", "jpg", "PNG", "PDF"].includes(fileType)) {
        this.$message.error("文件类型必须为pdf,png格式");
        return false;
      }
      if (file.size / 1024 / 1024 > 10) {
        this.$message.error({
          message: `上传文件大小不能超过10M!`,
        });
        return false;
      }
    },
    lookFile(item) {
      window.open(item.response.data.url); // 重新打开一个浏览器页进行预览
    },
    handleBack() {
      this.$emit("submitFormData");
    },
    handleSubmit(val) {
      let formData = [];
      // for (let key in val) {
      //   console.log(key);
      //   let findItem = this.formItemDoList.find((item) => item.field == key);
      //   findItem.defaultValue = val[key];
      //   // formData.push({
      //   //   formType: findItem.type,
      //   //   modelColumnName: findItem.field,
      //   //   formValue: val[key],
      //   // });
      // }
      for (let key in val) {
        let findItem = this.formItemDoList.find((item, index) => index == key);
        formData.push({
          formType: findItem.type,
          modelColumnName: findItem.field,
          formValue: val[key],
        });
      }
      if (!this.fileList.length) {
        this.$message.warning("请上传申请材料");
        return;
      }
      // 上传文件地址集合
      let fileUrlList = this.fileList.map((item) => {
        return { url: item.response.data.url, name: item.name };
      });
      this.$emit(
        "submitFormData",
        JSON.stringify(formData),
        "",
        JSON.stringify(fileUrlList)
      );
    },
    // 弹窗关闭
    handleClose() {
      this.toggleDialog();
    },
    toggleDialog(visible = false) {
      this.$emit("update:showDialog", visible);
    },
    // 提交
    handleRequestSuccess(val) {
      this.$emit("submitFormData", val);
    },
    // 表单格式转换
    getFormData(result) {
      let columnTypeString = [
        "input",
        "radio",
        "textarea",
        "button",
        "time-picker",
        "text",
      ];
      let columnTypeNumber = ["date", "rate"];
      let columnTypeArray = ["checkbox", "timerange", "daterange", "dates"];
      let columnTypeNumberEmpty = ["rate"];
      if (JSON.stringify(result.data) == "{}") {
        this.showTip = true;
        this.loading = false;
        return;
      }
      this.formDetail = result.data;
      this.formItemDoList = result.data.formItemDoList.map((item) => {
        return {
          field: item.modelColumnName,
          label: item.columnTitle,
          type: item.columnType,
          layout: 12,
          layoutReal: item.itemWidth,
          layout: item.itemWidth,
          default: item.defaultValue
            ? columnTypeString.includes(item.columnType)
              ? item.defaultValue
              : columnTypeNumber.includes(item.columnType)
                ? Number(item.defaultValue)
                : new Function("return " + item.defaultValue)()
            : columnTypeArray.includes(item.columnType)
              ? []
              : columnTypeNumberEmpty.includes(item.columnType)
                ? 0
                : "",
          required: item.itemRequired == 0 ? true : false,
          rules: item.validateRule ? JSON.parse(item.validateRule) : undefined,
          tip: item.itemTips,
          oneLine: item.itemOneLine == 0 ? true : undefined,
          isShowLabel: item.itemTitle == 0 ? false : undefined,
          color: item.itemTitleFont,
          strong: item.itemTitleStrong == 0 ? true : undefined,
          isOptions: item.itemOption ? true : undefined,
          createTime: item.createTime,
          options: item.itemOption ? JSON.parse(item.itemOption) : undefined,
          prop: item.itemOptionProp
            ? JSON.parse(item.itemOptionProp)
            : undefined,
          attrs: item.componentProp
            ? JSON.parse(item.componentProp)
            : undefined,
        };
      });
      let formDesc = this.arrToObject(this.formItemDoList);
      let formConfigAll = result.data.formProperty
        ? JSON.parse(result.data.formProperty)
        : {};
      formConfigAll.disabled = this.readonly;
      this.formConfig = JSON.stringify({
        formDesc: formDesc,
        formConfig: formConfigAll,
      });
      this.fileList = result.data.file ? result.data.file : [];
      this.pure = true;
      this.flag = true;
      this.loading = false;
      this.$nextTick(() => {
        this.formItemDoList.forEach((item, index) => {
          let dom = document.querySelectorAll(
            ".global-review .el-form .el-col"
          )[index];
          // 通过layout重新计算宽度
          if (dom) {
            dom.style.width = `${parseInt(
              (item.layoutReal / this.formDetail.formRow) * 100
            )}%`;
            dom.style.height = `51px`;
          }
          // 判断是否一行显示
          if (item.oneLine) {
            let bodyWidth = document.querySelector(".global-review  .el-form");
            let moveWidth =
              bodyWidth.clientWidth - dom.clientWidth - dom.offsetLeft - 30;
            dom.style.marginRight = `${moveWidth}px`;
          } else if (dom) {
            dom.style.marginRight = `0px`;
          }
          //let label = document.querySelectorAll(".el-form .el-form-item__label")[index];
          // 判断是否设置标题样式
          // if (item.color) {
          //   label.style.color = item.color;
          // } else {
          //   label.style.color = "#606266";
          // }
          // // 是否加粗
          // if (item.strong) {
          //   label.style.fontWeight = "600";
          // } else {
          //   label.style.fontWeight = "500";
          // }
        });
      });
    },
    // 获取流程实例的全局表单和表单数据
    async getFormById(id) {
      const result = await getFormById({
        id: id,
      });
      this.getFormData(result);
    },
    // 数组转对象
    arrToObject(arr) {
      return arr.reduce((map, item, currentIndex) => {
        map[currentIndex] = item;
        return map;
      }, {});
    },
    // 获取流程定义全局表单id
    async getFormKeyByDefId() {
      const result = await getFormKeyByDefId({
        processDefinitionId: this.processDefinitionId,
      });
      if (result.data.formId) {
        this.getFormById(result.data.formId);
      } else {
        this.$message.warning("流程暂未绑定表单");
      }
    },
    async getFromAndData() {
      const result = await getFromAndData({
        definitionId: this.processDefinitionId,
        instanceId: this.instanceId,
      });
      this.getFormData(result);
    },
    handleChange(response, file, fileList) {
      this.fileList = fileList.slice(-3);
    },
  },
  created() { },
  mounted() {
    this.detail = this.$route.query.detail;
    this.loading = true;
    if (this.instanceId) {
      this.getFromAndData();
    } else {
      this.getFormKeyByDefId();
    }
  },
};
</script>
<style scoped lang="scss">
.approval-form {
  margin: 10px 50px;
  height:100%;
  // height: calc( 100% - 260px);
  // overflow: auto;
  color: #cce3ff;
  font-size: 14px;
}

.apply-upload {
  display: flex;
  align-items: center;
  margin-bottom: 10px;

  &-title {
    margin: 0 14px;
  }

  &-name {
    margin-right: 10px;
    color: #03cbf6;
    cursor: pointer;
  }
}

::v-deep .f-render {
  background-color: #fff !important;
}

::v-deep .f-render-comp {
  width: 80px;
}

flag .add-form {
  height: 100vh;
  background-color: #fff;

  .title {
    margin: 0 auto;
    width: 80%;
    padding: 20px 0 20px 50px;
    border-bottom: 1px solid #dcdfe6;

    span {
      margin-left: 10px;
    }
  }
}

::v-deep .f-render-comp {
  display: block;
  width: 100px;
  text-align: center;
}

::v-deep .f-render-comps {
  display: flex;
  align-content: center;
  flex-wrap: wrap;
}

::v-deep .form-item {
  width: 100%;
}

::v-deep .f-render-comp-title {
  display: none;
}

::v-deep .el-row--flex.is-justify-center {
  justify-content: left;
}

::v-deep .el-form-item__content {
  .el-button {
    // display: none;
  }
}

::v-deep .ele-form-btns {
  // display: none;
}

::v-deep .el-col-24 {
  height: 59px !important;
}

::v-deep .el-col-18 {
  width: 90% !important;
}

::v-deep .el-col-12 {
  height: 59px !important;
}

::v-deep .el-empty {
  padding: 80px 0;
}

::v-deep .el-input {
  width: 100%;
}

::v-deep .el-date-editor {
  width: 100% !important;
}

::v-deep .ele-form-btns {
  width: 100% !important;
}

::v-deep .el-form-item__content .el-button:first-child::before {

  content: "提交";
}

::v-deep .el-form-item__content .el-button:last-of-type::before {
  // content: "返回";
}

::v-deep .el-form-item__content .el-button span {
  display: none;
}

::v-deep .el-form-item__content {
  color: #cce3f3;
}
</style>
